package models

import (
	"t11Lib/t11Errors"
	"t11Lib/t11Model"
)

type DeviceKv struct {
	//id为devId+key
	t11Model.BaseMdl
	DevId string
	Key   string
	Value string
}

func (self *DeviceKv) SetId(devId, key string) {
	self.Id = devId + "-" + key
	self.DevId = devId
}

type deviceStatusDao struct{}

var DeviceKvDao deviceStatusDao

func (self deviceStatusDao) CreateOrUpdate(conn *t11Model.DbConn, status *DeviceKv) t11Errors.T11Error {
	_, err := conn.InsertOrUpdate(status)
	return t11Errors.Wrap(err)
}

func (self deviceStatusDao) Delete(conn *t11Model.DbConn, item *DeviceKv) t11Errors.T11Error {
	_, err := conn.Delete(item)
	return t11Errors.Wrap(err)
}

func (self deviceStatusDao) GetByDevIds(conn *t11Model.DbConn, devIds []string) ([]*DeviceKv, t11Errors.T11Error) {
	if len(devIds) == 0 {
		return nil, nil
	}
	var ret []*DeviceKv
	_, err := conn.QueryTable(&DeviceKv{}).Filter("DevId__in", devIds).All(&ret)
	return ret, t11Errors.Wrap(err)
}

func (self deviceStatusDao) DeleteByDevId(conn *t11Model.DbConn, devIds []string) t11Errors.T11Error {
	if len(devIds) == 0 {
		return nil
	}
	_, err := conn.QueryTable(&DeviceKv{}).Filter("DevId__in", devIds).Delete()
	return t11Errors.Wrap(err)
}

func (self deviceStatusDao) GetByKey(conn *t11Model.DbConn, key string) (*DeviceKv, t11Errors.T11Error) {
	ret := &DeviceKv{}
	err := conn.QueryTable(ret).Filter("key", "id_" + key).One(ret)
	return ret, t11Errors.Wrap(err)
}
